import { _decorator, Node, AudioClip, randomRangeInt, instantiate, Vec3, v3, tween, UIOpacity, sp } from 'cc';
const { ccclass, property } = _decorator;

import TurkishTetris_GameDataConfig from "../../../../hall/Data/TurkishTetris_GameDataConfig";
import TurkishTetris_GameConfig from "../../../../hall/Data/TurkishTetris_GameConfig";
import { TurkishTetris_GameData } from "../../../../hall/Data/TurkishTetris_GameData";
import { CardType } from "../../../../hall/Data/TurkishTetris_GameEnum";
import TurkishTetris_CardGroup from "../Game/TurkishTetris_CardGroup";
import TurkishTetris_Grid from "../Game/TurkishTetris_Grid";
import TurkishTetris_AssetsLoad from "../Manager/TurkishTetris_AssetsLoad";
import TurkishTetris_UIManager from "../Manager/TurkishTetris_UIManager";
import TurkishTetris_GameManager from "../Manager/TurkishTetris_GameManager";
import TurkishTetris_TipScorePanel from "../UI/TurkishTetris_TipScorePanel";
import TurkishTetris_TipCOMBOPanel from "../UI/TurkishTetris_TipCOMBOPanel";
import { bdlMgr } from "../../../../../../Script/Manager/BundleManager_S";
import { SSS_Consts } from "../../../../../../Script/Data/SSS_Consts";
import { TurkishTetris_GameStorage } from "../../../../hall/Data/TurkishTetris_GameStorage";
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';

@ccclass('TurkishTetrisCardFunctions')
export default class TurkishTetris_CardFunctions {
    //    // 获取一张卡
    static GetCard(x: number, y: number) {
        if (TurkishTetris_GameData.arrCards[x] && TurkishTetris_GameData.arrCards[x][y]) {
            return TurkishTetris_GameData.arrCards[x][y];
        }

        return null;
    }
    //    // 获取Item
    static GetItem(arr, x: number, y: number) {
        if (arr[x] && arr[x][y]) {
            return arr[x][y];
        }

        return null;
    }
    //    // 获取同一行的左边
    static GetRowL(cardGroup: TurkishTetris_CardGroup) {
        let row = TurkishTetris_GameData.arrCardGroups[cardGroup.y];

        function compare(a, b) {
            if (a.x > b.x) return 1;
            if (b.x > a.x) return -1;

            return 0;
        }

        row.sort(compare);

        let index = row.indexOf(cardGroup);
        if (index === 0) {
            return -1;
        }

        let cardGroup_left: TurkishTetris_CardGroup = row[index - 1];

        let x_line: number = cardGroup_left.x + cardGroup_left.length - 1;

        return x_line;
    }
    //    // 获取同一行的右边
    static GetRowR(cardGroup: TurkishTetris_CardGroup) {
        let row = TurkishTetris_GameData.arrCardGroups[cardGroup.y];

        function compare(a, b) {
            if (a.x > b.x) return 1;
            if (b.x > a.x) return -1;

            return 0;
        }

        row.sort(compare);

        let index = row.indexOf(cardGroup);
        if (index === row.length - 1) {
            return TurkishTetris_GameConfig.col;
        }

        let cardGroup_left: TurkishTetris_CardGroup = row[index + 1];

        let x_line: number = cardGroup_left.x;

        return x_line;
    }
    //    /** 创建格子 */
    static CreateGrid(_id: number, x: number, y: number): TurkishTetris_Grid {
        const node: Node = instantiate(TurkishTetris_AssetsLoad.Instance.Grid);
        const scrGrid: TurkishTetris_Grid = node.getComponent(TurkishTetris_Grid);
        scrGrid.init(_id, x, y);
        TurkishTetris_UIManager.Instance.Root_grid.addChild(node);
        return scrGrid;
    }
    //    /** 创建牌组 */
    static CreateCardGroup(_id: number, _type: CardType, x: number, y: number, length: number, color: number, targetX: number = -1): TurkishTetris_CardGroup {
        const node: Node = instantiate(TurkishTetris_AssetsLoad.Instance.CardGroup);
        const cardGroup: TurkishTetris_CardGroup = node.getComponent(TurkishTetris_CardGroup);
        TurkishTetris_UIManager.Instance.Root_card.addChild(node);
        cardGroup.init(_id, _type, x, y, length, color, targetX);
        return cardGroup;
    }
    static GetCardGroupColorListByColor(color: number) {
        let list: TurkishTetris_CardGroup[] = [];
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];

            for (let index = 0; index < row.length; index++) {
                const cardGroup: TurkishTetris_CardGroup = row[index];

                if (cardGroup && cardGroup.type === CardType.Normal && cardGroup.color == color) {
                    list.push(cardGroup);
                }
            }
        }
        return list;
    }
    //    /**  */
    static GetCardGroupColorList() {
        let list = {};

        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];

            for (let index = 0; index < row.length; index++) {
                const cardGroup: TurkishTetris_CardGroup = row[index];

                if (cardGroup && cardGroup.type === CardType.Normal) {
                    if (!list[cardGroup.color]) {
                        list[cardGroup.color] = [];
                    }
                    list[cardGroup.color].push(cardGroup);
                }
            }
        }

        // console.log("list", list);

        let length = 0;
        for (const key in list) {
            if (Object.prototype.hasOwnProperty.call(list, key)) {
                const element = list[key];
                // console.log("element", element);
            }
        }

        return list;
    }
    //    /** 获取被切割的元素 */
    static GetRandomCardGroupCut(cardGroup_Super: TurkishTetris_CardGroup) {
        function checkArrHasEqualValue(arr1, arr2) {
            for (let i = 0; i < arr1.length; i++) {
                for (let j = 0; j < arr2.length; j++) {
                    if (arr1[i] == arr2[j]) {
                        return true;
                    }
                }
            }
            return false;
        }

        const y = cardGroup_Super.y;
        const row1 = TurkishTetris_GameData.arrCardGroups[y + 1];
        const row2 = TurkishTetris_GameData.arrCardGroups[y - 1];
        let row = [];
        if (row1) {
            row = row.concat(row1);
        }
        if (row2) {
            row = row.concat(row2);
        }

        // console.log("row", row);

        // cardGroup_Super.node.scale = 0.7;

        const data_cardGroup_Super = TurkishTetris_CardFunctions.GetCardGroupArray(cardGroup_Super);
        // console.log("data_cardGroup_Super", data_cardGroup_Super);
        let list: TurkishTetris_CardGroup[] = [];
        for (let index = 0; index < row.length; index++) {
            const cardGroup = row[index];
            let data = TurkishTetris_CardFunctions.GetCardGroupArray(cardGroup);
            // console.log("data", data);

            if (cardGroup.length > 1) {
                if (checkArrHasEqualValue(data_cardGroup_Super, data)) {
                    // return cardGroup;
                    list.push(cardGroup);
                }
            }
        }

        // return null;
        return list;
    }
    static GetCardGroupArray(cardGroup: TurkishTetris_CardGroup) {
        let array = [];

        for (let x = cardGroup.x; x < cardGroup.x + cardGroup.length; x++) {
            array.push(x);
        }

        return array;
    }
    //    /**  */
    static GetRandomCardGroupColor() {
        let list = TurkishTetris_CardFunctions.GetCardGroupColorList();

        let keys = Object.keys(list);
        // console.log("keys", keys);
        const random = randomRangeInt(0, keys.length);
        const key = keys[random];
        const item = list[key];
        // console.log("item", item);

        return item;
    }

    //    /** 获取最多的颜色的方块 */
    static GetLengthMaxCardGroupColor() {
        let list = TurkishTetris_CardFunctions.GetCardGroupColorList();

        let keys = Object.keys(list);
        // console.log("keys", keys);

        let item = list[keys[0]];
        for (let index = 0; index < keys.length; index++) {
            const element = list[keys[index]];
            // console.log("element1---", element);
            if (element.length > item.length) {
                item = element;
            }
        }

        // const random = randomRangeInt(0, keys.length);
        // const key = keys[random];
        // const item = list[key];
        // console.log("item----------", item);

        return item;
    }

    //    /** 方块是否可以下落到下一层 */
    static IsBlockCanFallNext(cardGroup: TurkishTetris_CardGroup) {
        let y_start: number = cardGroup.y;
        let y_nextRow: number = y_start - 1;

        if (y_nextRow >= 0) {
            let nextRow = TurkishTetris_CardFunctions.GetRowData(y_nextRow);
            // console.log(`nextRow`, nextRow);

            for (let x = cardGroup.x; x < cardGroup.x + cardGroup.length; x++) {
                // console.log(`x`, x);

                // console.log(`indexOf`, nextRow.indexOf(x));
                if (nextRow.indexOf(x) >= 0) {
                    return false;
                }
            }
        } else {
            return false;
        }

        return true;
    }
    //    /** 是否能消除 */
    static IsHasAllClear() {
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const rowData = TurkishTetris_CardFunctions.GetRowData(y);
            // console.log("rowData", rowData);
            if (rowData.length >= TurkishTetris_GameConfig.col) {
                return true;
            }
        }

        return false;
    }
    //    /** 获取行数 */
    static GetRowNumber(): number {
        let rowNumber: number = 0;

        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];
            if (row.length > 0) {
                rowNumber++;
            }
        }

        return rowNumber;
    }
    //    /** 获取特殊 */
    static GetSuper(cardType) {
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];

            for (let index = 0; index < row.length; index++) {
                const cardGroup: TurkishTetris_CardGroup = row[index];
                if (cardGroup.type == cardType) {
                    return cardGroup;
                }
            }
        }

        return null;
    }
    //    /** 获取随机一个普通块 */
    static GetRandomNormalCardGroup() {
        let newArr = TurkishTetris_GameData.arrCardGroups.filter((item, index, arr) => {
            return item.length > 0;
        });

        let fitArr = [];
        for (let rList of newArr) {
            let tmpList = rList.filter((item) => {
                return item.type == CardType.Normal;
            });
            fitArr.push(tmpList);
        }
        let random_y: number = randomRangeInt(0, fitArr.length);
        const row = fitArr[random_y];

        let randomIndex: number = randomRangeInt(0, row.length);
        const cardGroup: TurkishTetris_CardGroup = row[randomIndex];

        return cardGroup;
    }
    //    /** 获取特殊 */
    static GetSuper_y(y: number) {
        const row = TurkishTetris_GameData.arrCardGroups[y];

        let superList: TurkishTetris_CardGroup[] = [];
        for (let index = 0; index < row.length; index++) {
            const cardGroup: TurkishTetris_CardGroup = row[index];
            if (cardGroup.type !== CardType.Normal) {
                // return cardGroup;
                superList.push(cardGroup);
            }
        }
        // 从小到大，闪电优先级较高
        superList = superList.filter((item) => {
            return item.isItemCast == false;
        });
        superList.sort((a, b) => {
            return a.type - b.type;
        });
        if (superList.length > 0) {
            return superList[0];
        }

        return null;
    }
    //    /** 是否存在特殊 */
    static HasSuper_y(y: number) {
        const row = TurkishTetris_GameData.arrCardGroups[y];
        for (const cardGroup of row) {
            if (cardGroup.type !== CardType.Normal) {
                return true;
            }
        }
        return false;
    }
    //    /** 闪电 */
    static DoSuper_Flash(card_super: TurkishTetris_CardGroup, _callback: Function = null, srcColor?: number) {
        console.log("闪电");
        // AudioPlayer.getInstance().playSound("sound/flash", false, hallFunc.xwResBundle);


        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/电流`, AudioClip).then(res => {
            if (res) {
                SSS_AudioManager.Instance.playSFX(res, false);
                // audioEngine.setVolume(audioId, 0.6);
            }
        });

        card_super.FlashFrame.active = true;
        card_super.FlashFrame.getComponent(sp.Skeleton).setAnimation(0, "animation", true); // 立刻指定动画，避免先闪 setup pose

        card_super.FlashFrame.getComponent(UIOpacity).opacity = 0;
        tween(card_super.FlashFrame.getComponent(UIOpacity))
            .to(0.2, { opacity: 255 })
            .delay(0.01)
            .call(() => {
                f1();
            })
            .start();

        let f1 = () => {
            let list: TurkishTetris_CardGroup[];
            if (srcColor != null) {
                list = TurkishTetris_CardFunctions.GetCardGroupColorListByColor(srcColor);
            } else {
                list = TurkishTetris_CardFunctions.GetLengthMaxCardGroupColor();
            }
            for (let index = list.length - 1; index >= 0; index--) {
                const element: TurkishTetris_CardGroup = list[index];
                // console.log("element----", element);

                {
                    let startPos: Vec3 = card_super.node.position;

                    let card_normal = element; // CardFunctions.GetRandomCardGroup();
                    card_normal.FlashFrame.active = true;
                    card_normal.FlashFrame.getComponent(UIOpacity).opacity = 0;

                    // console.log(card_normal.node.position);

                    let x = card_normal.node.position.x - card_super.node.position.x;
                    let y = card_normal.node.position.y - card_super.node.position.y;
                    let endPos: Vec3 = v3(x, y, 0);
                    // console.log(endPos.x, endPos.y);

                    // EffectManager.CreateLightningSprite(startPos, endPos);

                    tween(card_normal.FlashFrame.getComponent(UIOpacity))
                        .to(0.6, { opacity: 255 })
                        .delay(0.3)
                        // .to(0.1, { scale: 1 })
                        // .repeat(2, tween().to(0.1, { scale: 0.6 }).to(0.1, { scale: 1 }))
                        .call(() => {
                            element?.DestroyAnimation();
                            TurkishTetris_CardFunctions.RemoveOneCardGroup(element);

                            if (index === 0) {
                                TurkishTetris_CardFunctions.DestroyAllFlashLine();
                                if (_callback) {
                                    _callback();
                                }
                            }
                        })
                        .start();
                }

                // tween(element.node)
                //     .repeat(2, tween().to(0.1, { scale: 0.6 }).to(0.1, { scale: 1 }))
                //     .call(() => {
                //         element?.DestroyAnimation();
                //         CardFunctions.RemoveOneCardGroup(element);

                //         if (index === list.length - 1) {
                //             if (_callback) {
                //                 _callback();
                //             }
                //         }
                //     })
                //     .start();
            }
        };
    }
    static DestroyAllFlashLine() {
        for (let index = 0; index < TurkishTetris_UIManager.Instance.Root_effect.children.length; index++) {
            const element: Node = TurkishTetris_UIManager.Instance.Root_effect.children[index];
            element?.destroy();
        }
    }
    //    /** 切割 */
    static DoSuper_Cut(cardGroup_Super, _callback: Function = null) {
        console.log("切割");

        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/切割`, AudioClip).then(res => {
            if (res) {
                SSS_AudioManager.Instance.playSFX(res, false);
                // audioEngine.setVolume(audioId, 0.6);
            }
        });

        const cardGroupList: TurkishTetris_CardGroup[] = TurkishTetris_CardFunctions.GetRandomCardGroupCut(cardGroup_Super);
        if (!cardGroupList || cardGroupList.length == 0) {
            if (_callback) {
                _callback();
            }
        } else {
            let toCutTotalCnt = cardGroupList.length;
            let cutEndCnt = 0;
            for (const cardGroup of cardGroupList) {
                cardGroup.CutBlock(() => {
                    cutEndCnt++;
                    if (cutEndCnt == toCutTotalCnt) {
                        if (_callback) {
                            _callback();
                        }
                    }
                });
            }
        }
    }
    //    /**  */
    static HasSuper() {
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];

            for (let index = 0; index < row.length; index++) {
                const cardGroup: TurkishTetris_CardGroup = row[index];
                if (cardGroup.type !== CardType.Normal) {
                    return true;
                }
            }
        }

        return false;
    }
    //    /** 是否能消除 */
    static IsHasClearRow(y) {
        const rowData = TurkishTetris_CardFunctions.GetRowData(y);
        // console.log("rowData", rowData);
        if (rowData.length >= TurkishTetris_GameConfig.col) {
            return true;
        }

        return false;
    }

    //    /** 消除单行 */
    static ClearOneRow(y) {
        let scoreAll = 0;

        const row = TurkishTetris_GameData.arrCardGroups[y];
        for (let index = 0; index < row.length; index++) {
            const cardGroup = row[index];
            cardGroup?.DestroyAnimation();
            // cardGroup.Destroy();

            if (TurkishTetris_GameData.gameMode == 0 && cardGroup) {
                const score = TurkishTetris_CardFunctions.GetScore(cardGroup.length);
                scoreAll += score;
            }
        }

        console.log(`消除单行`);

        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/符文碎裂`, AudioClip).then(res => {
            if (res) {
                SSS_AudioManager.Instance.playSFX(res, false);
                // audioEngine.setVolume(audioId, 0.6);
            }
        });



        if (scoreAll > 0) {
            TurkishTetris_TipScorePanel.Instance.Show(`${scoreAll}`);
        }

        TurkishTetris_GameData.arrCardGroups[y] = [];

        if (TurkishTetris_GameData.gameMode == 0 && !TurkishTetris_GameStorage.data.GameData.isHasSkill) {
            TurkishTetris_GameStorage.data.GameData.clearRowNumber++;



            TurkishTetris_GameStorage.saveData();
        }

        let clearSound = "sound/clear";
        if (TurkishTetris_GameData.gameMode == 1) {
            clearSound = "sound/clearDesert";
        }
        // AudioPlayer.getInstance().playSound(clearSound, false, hallFunc.xwResBundle);
    }
    //    /** 从数组中移除 */
    static RemoveOneCardGroup(cardGroup: TurkishTetris_CardGroup) {
        if (!cardGroup) {
            return;
        }

        let y_start: number = cardGroup.y;
        let startRow = TurkishTetris_GameData.arrCardGroups[y_start];
        startRow.splice(startRow.indexOf(cardGroup), 1);
    }
    static doNext(_y: number, _callback: Function = null) {
        let y = _y;
        if (y < TurkishTetris_GameData.arrCardGroups.length) {
            let isHasClearRow = TurkishTetris_CardFunctions.IsHasClearRow(y);
            if (isHasClearRow) {
                TurkishTetris_GameData.ContinuousEliminationNumber++;

                TurkishTetris_GameManager.Instance.scheduleOnce(() => {
                    let hasSuper = TurkishTetris_CardFunctions.HasSuper_y(y);
                    if (hasSuper) {
                        this.castCardItem(y);
                    } else {
                        TurkishTetris_CardFunctions.ClearOneRow(y);
                        if (TurkishTetris_GameData.gameMode == 0 && TurkishTetris_GameData.ContinuousEliminationNumber > 1) {
                            TurkishTetris_TipCOMBOPanel.Instance.Show(`${TurkishTetris_GameData.ContinuousEliminationNumber - 1}x连击`);
                        }

                        y++;
                        TurkishTetris_CardFunctions.doNext(y);
                    }
                }, 0.2);
            } else {
                y++;
                TurkishTetris_CardFunctions.doNext(y);
            }
        } else {
            TurkishTetris_GameManager.Main(7);
        }
    }
    //    /** 消除所有能消的 */
    static ClearAllRow() {
        let y = 0;

        TurkishTetris_CardFunctions.doNext(y);
    }
    static castCardItem(y: number) {
        console.log(`castCardItem-----------`);
        let cardGroup_Super = TurkishTetris_CardFunctions.GetSuper_y(y);
        if (cardGroup_Super) {
            cardGroup_Super.isItemCast = true;
            if (cardGroup_Super.type === CardType.Super_1) {
                // 雷电
                // let data = {
                //     index: 0,
                //     callback: () => {
                TurkishTetris_CardFunctions.DoSuper_Flash(cardGroup_Super, () => {
                    TurkishTetris_CardFunctions.tryClearOneRow(y);
                });
                //     },
                //     // callback_close: () => {
                //     //     TurkishTetris_CardFunctions.tryClearOneRow(y);
                //     // },
                // };
                // hallFunc.showPanel(HallResConstant.PREFABS_PATH.SkillPanel, data);
            } else if (cardGroup_Super.type === CardType.Super_2) {
                // 切割
                let cutFun = () => {
                    TurkishTetris_CardFunctions.DoSuper_Cut(cardGroup_Super, () => {
                        TurkishTetris_CardFunctions.tryClearOneRow(y);
                    });
                };
                // let hasWatchCutItemTip = LocalStorage.getInstance().getBool(HallConst.LocalStorageKey.hasWatchCutItemTip, false);
                // if (hasWatchCutItemTip) {
                cutFun();
                // } 
                // else {
                // let data = {
                //     index: 1,
                //     callback: () => {
                //         cutFun();
                //     },
                //     callback_close: () => {
                //         TurkishTetris_CardFunctions.tryClearOneRow(y);
                //     },
                // };
                // hallFunc.showPanel(HallResConstant.PREFABS_PATH.skillCutPanel, data);
                // LocalStorage.getInstance().setBool(HallConst.LocalStorageKey.hasWatchCutItemTip, true);
                // }
            }
        }
    }
    static ToColor() {
        // let m = this.icon.getMaterials();
        // console.log(`m`, m);
        // this.icon.setMaterial(0, m[1]);

        for (let index = 0; index < TurkishTetris_GameConfig.row; index++) {
            const row = TurkishTetris_GameData.arrCardGroups[index];
            for (const cardGroup of row) {
                // tween(cardGroup.node)
                //     .delay((index + 1) * 0.1)
                //     .call(() => {
                cardGroup.ToColor();
                // })
                // .start();
            }
        }
    }
    static tryClearOneRow(y: number) {
        let cardGroup_Super = TurkishTetris_CardFunctions.GetSuper_y(y);
        if (cardGroup_Super) {
            TurkishTetris_CardFunctions.castCardItem(y);
        } else {
            // 如果一行没有其他道具了就执行清除当前行

            TurkishTetris_CardFunctions.ClearOneRow(y);
            TurkishTetris_GameManager.Instance.scheduleOnce(() => {
                // eslint-disable-next-line no-param-reassign
                y++;
                TurkishTetris_CardFunctions.doNext(y);
            }, 0.4);
        }
    }

    //    /** 方块是否可以下落到下一层 */
    static BlockFallNext(cardGroup: TurkishTetris_CardGroup) {
        let y_start: number = cardGroup.y;
        let y_nextRow: number = y_start - 1;

        cardGroup.y = y_nextRow;

        TurkishTetris_GameData.arrCardGroups[y_nextRow].push(cardGroup);
        let startRow = TurkishTetris_GameData.arrCardGroups[y_start];
        startRow.splice(startRow.indexOf(cardGroup), 1);
    }
    //    /** 方块下落到不能下落 */
    static BlockFallToCanNotFall(cardGroup: TurkishTetris_CardGroup) {
        let isFall: boolean = TurkishTetris_CardFunctions.IsBlockCanFallNext(cardGroup);
        while (isFall) {
            TurkishTetris_CardFunctions.BlockFallNext(cardGroup);
            isFall = TurkishTetris_CardFunctions.IsBlockCanFallNext(cardGroup);
        }
    }
    //    /** 所有方块下落到不能下落 */
    static AllBlockFallToCanNotFall() {
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];
            for (let index = row.length - 1; index >= 0; index--) {
                const cardGroup = row[index];
                // console.log(`cardGroup`, cardGroup.x, cardGroup.y, cardGroup);
                TurkishTetris_CardFunctions.BlockFallToCanNotFall(cardGroup);

                cardGroup.movePosition();
                // cardGroup.InitPosition();
            }
        }
    }
    //    /** 获取一行数据 */
    static GetRowData(y: number) {
        let row = [];

        const data = TurkishTetris_GameData.arrCardGroups[y];
        // console.log(`data`, data);

        for (let index = 0; index < data.length; index++) {
            const cardGroup = data[index];
            // console.log(`cardGroup`, cardGroup);

            for (let x = cardGroup.x; x < cardGroup.x + cardGroup.length; x++) {
                // console.log(`x`, x);
                row.push(x);
            }
        }

        // console.log(`row`, row);

        return row;
    }
    //    /**  */
    static MoveBlockY(cardGroup: TurkishTetris_CardGroup, dir_y: number) {
        let y_start: number = cardGroup.y;
        let y_nextRow: number = y_start + dir_y;

        cardGroup.y = y_nextRow;

        TurkishTetris_GameData.arrCardGroups[y_nextRow].push(cardGroup);
        let startRow = TurkishTetris_GameData.arrCardGroups[y_start];
        startRow.splice(startRow.indexOf(cardGroup), 1);
    }
    //    /** 获取一行数据 */
    static MoveOneRow(y: number, dir_y: number) {
        let row = TurkishTetris_GameData.arrCardGroups[y];

        for (let index = row.length - 1; index >= 0; index--) {
            const cardGroup = row[index];
            TurkishTetris_CardFunctions.MoveBlockY(cardGroup, dir_y);
            cardGroup.movePosition();
            // cardGroup.InitPosition();
        }
    }
    //    /** 移动所有 */
    //    // >0上移 <0下移
    static MoveAllRow(dir_y: number) {
        for (let y = TurkishTetris_GameData.arrCardGroups.length - 1; y >= 0; y--) {
            TurkishTetris_CardFunctions.MoveOneRow(y, dir_y);
        }
    }
    //    // 检测是否有未下落的卡牌-所有
    static GetHasNotFallCardAll() {
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];
            for (let index = 0; index < row.length; index++) {
                const cardGroup = row[index];
                // console.log(`cardGroup`, cardGroup.x, cardGroup.y, cardGroup);
                const isBlockCanFallNext: boolean = TurkishTetris_CardFunctions.IsBlockCanFallNext(cardGroup);
                if (isBlockCanFallNext) {
                    return true;
                }
            }
        }

        return false;
    }
    static GetBlockPercent(level: number) {
        const data = TurkishTetris_GameDataConfig.BlockPercent[level];

        console.log(`level----------`, level);
        console.log(`data----------`, data);

        let random = randomRangeInt(0, 100);
        // console.log("data", data);
        // console.log("random", random);
        let index = 0;
        let value = data[index];
        while (random >= value) {
            index++;
            value = data[index];

            // console.log("index", index);
            // console.log("value", value);
        }
        // console.log("index", index);

        return index;
    }
    static GetFiXNewLineBlockData(y) {
        let data = [
            // 1
            [
                { x: 1, y: -1, color: 0, type: CardType.Normal, length: 2, targetX: 3 },
                { x: 3, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: 5 },
            ],
            [
                { x: 0, y: -1, color: 0, type: CardType.Normal, length: 2, targetX: -1 },
                { x: 2, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: -1 },
            ],
            // 2
            [
                { x: 0, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: -1 },
                { x: 5, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: -1 },
            ],
            // 3
            [
                { x: 1, y: -1, color: 0, type: CardType.Normal, length: 2, targetX: -1 },
                { x: 3, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: -1 },
            ],
            [
                { x: 1, y: -1, color: 0, type: CardType.Normal, length: 2, targetX: -1 },
                { x: 3, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: -1 },
            ],
            [
                { x: 1, y: -1, color: 0, type: CardType.Normal, length: 2, targetX: -1 },
                { x: 3, y: -1, color: 0, type: CardType.Normal, length: 3, targetX: -1 },
            ],
        ];

        // console.log("GameStorage.data.guideStep_line", GameStorage.data.guideStep_line);

        let newData = [];
        newData = data[TurkishTetris_GameStorage.data.guideStep_line];

        // console.log("newData", newData);

        TurkishTetris_GameStorage.data.guideStep_line++;
        TurkishTetris_GameStorage.saveData();

        return newData;
    }
    //    // static tIndex = 0;
    static GetNewLineBlockData(y) {
        let newData = [];

        let array = [0];
        let sum = 1;
        while (sum < TurkishTetris_GameConfig.col) {
            let max = TurkishTetris_GameConfig.col - sum;
            max = max < 4 ? max : 4;

            let random;
            if (max >= 4) {
                random = TurkishTetris_CardFunctions.GetBlockPercent(TurkishTetris_GameData.GetLevel());
            } else {
                random = randomRangeInt(0, max + 1);
            }

            let length: number = random === 0 ? 1 : random;

            sum += length;

            array.push(random);
        }
        // console.log(`sum`, sum);
        // console.log(`array`, array);

        function randomsort(a, b) {
            return Math.random() > 0.5 ? 1 : -1;
        }

        array.sort(randomsort);

        // console.log(`array`, array);
        // console.log(`newData`, newData);

        let sum2 = 0;
        for (let index = 0; index < array.length; index++) {
            const random = array[index];
            const length = random === 0 ? 1 : random;

            if (random > 0) {
                let item = { x: sum2, y: y, color: 0, type: CardType.Normal, length: length };
                newData.push(item);
            }

            sum2 += length;
        }


        if (TurkishTetris_GameData.IsNewGuide()) {
            newData = TurkishTetris_CardFunctions.GetFiXNewLineBlockData(y);

            // if (GameStorage.data.guideStep === 0) {
            //     GuidePanel.Instance.ShowOn();
            //     GuidePanel.Instance.Move_1();
            // }
            // if (GameStorage.data.guideStep === 1) {
            //     GuidePanel.Instance.ShowOn();
            //     GuidePanel.Instance.Move_2();
            // }
        }

        return newData;
    }
    //    // 最下面一行
    static NewLineBlock_0() {
        for (let index = 0; index < TurkishTetris_GameData.arrCardGroups_next.length; index++) {
            const cardGroup = TurkishTetris_GameData.arrCardGroups_next[index];
            cardGroup.y = 0;
            cardGroup.InitPosition();
            cardGroup.node.active = true;
            TurkishTetris_GameData.arrCardGroups[0].push(cardGroup);
        }
    }
    //    // 最下面一行的下面一行
    static NewLineBlock_next() {
        TurkishTetris_GameData.arrCardGroups_next = [];

        const y = -1;
        let newData = TurkishTetris_CardFunctions.GetNewLineBlockData(y);
        // xwLog("newData", newData);
        for (let index = 0; index < newData.length; index++) {
            const element = newData[index];
            const x_start = element.x;
            const length = element.length;
            const x_end = x_start + length;
            const y = element.y;
            const id = 0;
            const color = randomRangeInt(0, TurkishTetris_GameConfig.colors.length);
            const targetX = element.targetX;

            const cardType: CardType = CardType.Normal;
            const cardGroup: TurkishTetris_CardGroup = TurkishTetris_CardFunctions.CreateCardGroup(id, cardType, x_start, y, length, color, targetX);
            TurkishTetris_GameData.arrCardGroups_next.push(cardGroup);
        }

        if (!TurkishTetris_GameData.IsNewGuide()) {
            const row = TurkishTetris_GameData.arrCardGroups_next;
            let bOneRow = row.filter((item) => {
                return item.length > 1;
            });
            if (bOneRow.length > 0) {
                const cardType: CardType = TurkishTetris_CardFunctions.GetType(TurkishTetris_GameData.GetLevel());
                let random = randomRangeInt(0, bOneRow.length);
                const cardGroup: TurkishTetris_CardGroup = bOneRow[random];

                // if (cardType == CardType.Super_1 && cardGroup.length == 1) {
                //     // 雷电方块-道具方块只刷新在2/3/4格上。
                //     xwLog("NewLineBlock_next cardType 1 闪电 格子是0 不生成闪电");
                //     return;
                // }
                cardGroup.type = cardType;
                cardGroup.Init();
            }
        }
    }
    static GetType(level: number = TurkishTetris_GameData.GetLevel()) {
        const data = TurkishTetris_GameDataConfig.SpecialPercent[level];

        let random = randomRangeInt(0, 100);
        // console.log("data", data);
        // console.log("random", random);
        let index = 0;
        let value = data[index];
        while (random >= value) {
            index++;
            value = data[index];

            // console.log("index", index);
            // console.log("value", value);
        }
        // console.log("index", index);

        if (index != CardType.Normal) {
            let cardGroup_super = TurkishTetris_CardFunctions.GetSuper(index);
            if (cardGroup_super) {
                // 有相同的了，返回
                return 0;
            }
        }

        return index;
    }
    //    //
    static GetScore(block_length: number) {
        let score: number = 0;
        const score_base: number = TurkishTetris_GameDataConfig.BasicScore[block_length - 1];
        const lianjishu: number = TurkishTetris_GameData.ContinuousEliminationNumber;
        score = score_base * (TurkishTetris_GameData.GetLevel() + 1) * lianjishu;

        return score;
    }
    //    /**
    //     * 闪电特效
    //     * @returns
    //     */
    static GetColorData() {
        let data = [];

        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];
            for (let index = 0; index < row.length; index++) {
                const cardGroup: TurkishTetris_CardGroup = row[index];
                if (cardGroup.type != CardType.Normal) {
                    // 道具方块不参与判断
                    continue;
                }
                let arr = data.filter((item) => {
                    return item.color == cardGroup.color;
                });

                let value = arr[0];
                let item: any;
                if (!value) {
                    item = {};
                    item.color = cardGroup.color;
                    item.array = [];
                    item.array.push(cardGroup);
                    data.push(item);
                } else {
                    item = value;
                    item.array.push(cardGroup);
                }
            }
        }
        console.log(`data222`, data);

        let toSuperCard: TurkishTetris_CardGroup;

        // 为什么不放在上面，原始过滤长度大于1的group，是因为1同样要算个数
        let newArray = [];
        if (data.length > 0) {
            newArray = data.sort((a, b) => {
                let aBiggerOne = a.array.filter((item: TurkishTetris_CardGroup) => {
                    return item.length > 1;
                });
                let bBiggerOne = b.array.filter((item: TurkishTetris_CardGroup) => {
                    return item.length > 1;
                });
                if (aBiggerOne.length == 0) {
                    return 1;
                }
                if (bBiggerOne.length == 0) {
                    return -1;
                }
                return b.array.length - a.array.length;
            });

            let colors = newArray[0];

            let cBiggerOne = colors.array.filter((item: TurkishTetris_CardGroup) => {
                return item.length > 1;
            });

            toSuperCard = cBiggerOne[0];
        }

        return toSuperCard;
        // return newArray;
    }
    //    /** 获取随机一个最大方块 */
    static GetMaxNormalBlock() {
        let data = [];
        for (let y = 0; y < TurkishTetris_GameData.arrCardGroups.length; y++) {
            const row = TurkishTetris_GameData.arrCardGroups[y];
            for (let index = 0; index < row.length; index++) {
                const cardGroup: TurkishTetris_CardGroup = row[index];
                if (cardGroup.type == CardType.Normal) {
                    data.push(cardGroup);
                }
            }
        }

        let newArray = [];
        if (data.length > 0) {
            newArray = data.sort((a, b) => {
                return b.length - a.length;
            });
        }

        let maxBlock: TurkishTetris_CardGroup = newArray[0];

        return maxBlock;
    }

    static GetAll3ArrayY() { }
    static GetAll3ArrayX() { }
    static Check3Match(array: any = null) { }
    static RefreshAll3Card() { }
    static IsCan3Xiao() { }

    //    // 是否存在Grid
    static HasGrid(x: number, y: number): boolean {
        if (TurkishTetris_GameData.arrGrids[x] && TurkishTetris_GameData.arrGrids[x][y] && TurkishTetris_GameData.arrGrids[x][y].id >= 0) {
            return true;
        } else {
            return false;
        }
    }
}